<!-- eslint-disable vue/multi-word-component-names -->
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { ref } from 'vue'
import { noCodeLoginApi } from '@/api/login'
import { useUserStore } from '@/stores'
import { ElLoading, ElMessage } from 'element-plus'
import { onMounted } from 'vue'
import { ordinaryApplicationArry } from './menu'

let loading: any = null
const store = useUserStore() // 用户信息
const route = useRoute()
console.log(route.query)

const loginFrom = ref<any>({
  telephone: route.query.telephone || '',
  token: route.query.token || ''
})

const router = useRouter() // 路由
const loginFn = async (form: any) => {
  loading = ElLoading.service({
    lock: true,
    text: '页面正在加载中，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)'
  })
  await noCodeLoginApi(form)
    .then((res: any) => {
      if (res.code === 0) {
        store.setPathsArry(ordinaryApplicationArry)
        store.setToken(res.message.token)
        store.setAppInfo(res.message.apps)
        store.setNavInfo(res.message.menus)
        store.setUser(res.message.sys)
        store.setReturnUrl(res.message.url)

        store.creatNavBar()
        router.push({ path: '/home' })
        ElMessage({ message: '登录成功！', type: 'success' })
      } else {
        router.push({ path: '/login' })
        ElMessage({ message: res.message, type: 'error' })
      }
    })
    .catch((err) => {
      router.push({ path: '/login' })
      ElMessage({ message: err, type: 'error' })
    })
    .finally(() => {
      loading.close()
    })
}

onMounted(() => {
  const params = {
    telephone: loginFrom.value.telephone,
    token: loginFrom.value.token
  }
  loginFn(params)
})
</script>
